from PyQt5.QtWidgets import QTableWidgetItem, QLabel, QHBoxLayout, QWidget, QMenu, QMessageBox
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import Qt, QPoint

from common.logger import logger
from common.retcode import RetCode
from common.utils import get_file_size_str
from api.recycle import RecycleAction

class MainRecycleTable():
	def __init__(self, main_win):
		self._main_win = main_win

		self._recycle_list = None

		self.initWidgets()

	def initWidgets(self):
		self._main_win.pushButtonRecycleRefresh.clicked.connect(self.onClickedRecycleRefresh)
		self._main_win.pushButtonRecycleRestore.clicked.connect(self.onClickedRecycleRestore)
		self._main_win.pushButtonRecycleDelete.clicked.connect(self.onClickedRecycleDelete)
		self._main_win.pushButtonRecycleClear.clicked.connect(self.onClickedRecycleClear)

		self._main_win.tableWidgetRecycle.horizontalHeader().setFixedHeight(50) ##设置表头高度
		self._main_win.tableWidgetRecycle.horizontalHeader().resizeSection(0, 300) #设置列的宽度
		self._main_win.tableWidgetRecycle.horizontalHeader().resizeSection(1, 150) #设置列的宽度
		self._main_win.tableWidgetRecycle.horizontalHeader().resizeSection(2, 100) #设置列的宽度
		self._main_win.tableWidgetRecycle.horizontalHeader().resizeSection(3, 200) #设置列的宽度

		self._main_win.tableWidgetRecycle.horizontalHeader().setSectionsClickable(False) #可以禁止点击表头的列

		self._main_win.tableWidgetRecycle.setContextMenuPolicy(Qt.CustomContextMenu)  #允许右键产生子菜单
		self._main_win.tableWidgetRecycle.customContextMenuRequested.connect(self.generateRecycleOptMenu)  #右键菜单

		self._main_win.tableWidgetRecycle.itemSelectionChanged.connect(self.onRecycleTableSelectionChanged) # 点选事件

	########################################################################
	
	def onShowWindow(self):
		self.setRecycleOperationEnabled(False)

	def setRecycleOperationEnabled(self, is_enabled):
		self._main_win.pushButtonRecycleRestore.setEnabled(is_enabled)
		self._main_win.pushButtonRecycleDelete.setEnabled(is_enabled)

	########################################################################
	
	def getRecycleList(self):
		recycle_action = RecycleAction(self._main_win._sess_wp)
		rec_file_list = recycle_action.get_rec_file_list()
		print(rec_file_list)

		self._main_win.tableWidgetRecycle.setRowCount(len(rec_file_list))
		row = 0
		for rec_info in rec_file_list:

			fileIconLabel = self._main_win.getFileIconLabel(rec_info)

			fileNameLabel = QLabel()
			fileNameLabel.setText(rec_info.name)
			fileNameLayout = QHBoxLayout()
			fileNameLayout.setAlignment(Qt.AlignLeft)
			fileNameLayout.addWidget(fileIconLabel)
			fileNameLayout.addWidget(fileNameLabel)
			fileNameWidget = QWidget()
			fileNameWidget.setLayout(fileNameLayout)


			sizeStr = ''
			if rec_info.isFolder:
				if int(rec_info.id) > 0:
					sizeStr = '文件夹'
				else:
					sizeStr = '系统文件夹'
			else:
				sizeStr = get_file_size_str(rec_info.size)
			sizeItem = QTableWidgetItem(sizeStr)
			sizeItem.setTextAlignment(Qt.AlignCenter)

			isFamilyItem = QTableWidgetItem('是' if rec_info.isFamily else '否')
			isFamilyItem.setTextAlignment(Qt.AlignCenter)

			optimeItem = QTableWidgetItem(rec_info.optime)
			optimeItem.setTextAlignment(Qt.AlignCenter)

			ctimeItem = QTableWidgetItem(rec_info.ctime)
			ctimeItem.setTextAlignment(Qt.AlignCenter)

			self._main_win.tableWidgetRecycle.setCellWidget(row, 0, fileNameWidget)
			self._main_win.tableWidgetRecycle.setItem(row, 1, sizeItem)
			self._main_win.tableWidgetRecycle.setItem(row, 2, isFamilyItem)
			self._main_win.tableWidgetRecycle.setItem(row, 3, optimeItem)
			self._main_win.tableWidgetRecycle.setItem(row, 4, ctimeItem)

			row += 1

		self._recycle_list = rec_file_list

	def generateRecycleOptMenu(self):
		row_num = -1
		for idx in self._main_win.tableWidgetRecycle.selectionModel().selection().indexes():
			row_num = idx.row()

		if row_num < 0:
			return

		if row_num >= len(self._recycle_list):
			return

		cur_file = self._recycle_list[row_num]

		menu = QMenu()
		item1 = menu.addAction(u"还原文件")
		item2 = menu.addAction(u"删除文件")
		action = menu.exec_(self._main_win.tableWidgetRecycle.mapToGlobal(pos + QPoint(0, 30)))
		if action == item1:
			self.recycleRestore(cur_file)
		elif action == item2:
			self.recycleDelete(cur_file)
		else:
			return

	def onRecycleTableSelectionChanged(self):
		items = self._main_win.tableWidgetRecycle.selectedItems()
		if items and len(items) > 0:
			self.setRecycleOperationEnabled(True)
		else:
			self.setRecycleOperationEnabled(False)

	def getRecycleFileSeleted(self):
		items = self._main_win.tableWidgetRecycle.selectedItems()
		if items and len(items) > 0:
			self._recycle_list[items[0].row()]
		else:
			return None 

	def onClickedRecycleRefresh(self):
		self.getRecycleList()

	def onClickedRecycleRestore(self):
		file_info = self.getRecycleFileSeleted()
		if not file_info:
			QMessageBox.information(self._main_win, "提示", "请先选择需要操作的文件")
			return
		self.recycleRestore(file_info)

	def onClickedRecycleDelete(self):
		file_info = self.getRecycleFileSeleted()
		if not file_info:
			QMessageBox.information(self._main_win, "提示", "请先选择需要操作的文件")
			return
		self.recycleDelete(file_info)
		
	def onClickedRecycleClear(self):
		if len(self._recycle_list) <= 0:
			QMessageBox.information(self._main_win, "提示", "目前回收站没有文件")
			return
		msgBox = QMessageBox()
		msgBox.setWindowTitle('清空回收站')
		msgBox.setIcon(QMessageBox.Warning)
		icon = QIcon()
		icon.addPixmap(QPixmap(":/icon/icons/logo.png"), QIcon.Normal, QIcon.Off)
		msgBox.setWindowIcon(icon)
		msgBox.setText(f'确定要清空回收站吗？')
		btnOK = msgBox.addButton('确定', QMessageBox.AcceptRole)
		btnCancel = msgBox.addButton('取消', QMessageBox.RejectRole)
		msgBox.setDefaultButton(btnOK)
		reply = msgBox.exec()

		if reply != QMessageBox.AcceptRole:
			return
		recycle_action = RecycleAction(self._main_win._sess_wp)
		code = recycle_action.rec_empty(self._recycle_list[0])
		if code == RetCode.SUCCESS:
			self.getRecycleList()
		else:
			QMessageBox.information(self._main_win, "提示", "清空回收站失败")


	def recycleRestore(self, file_info):
		msgBox = QMessageBox()
		msgBox.setWindowTitle('还原文件/文件夹')
		msgBox.setIcon(QMessageBox.Warning)
		icon = QIcon()
		icon.addPixmap(QPixmap(":/icon/icons/logo.png"), QIcon.Normal, QIcon.Off)
		msgBox.setWindowIcon(icon)
		file_type = '文件夹' if file_info.isFolder else '文件'
		msgBox.setText(f'确定要还原{file_type}[{file_info.name}]吗？')
		btnOK = msgBox.addButton('确定', QMessageBox.AcceptRole)
		btnCancel = msgBox.addButton('取消', QMessageBox.RejectRole)
		msgBox.setDefaultButton(btnOK)
		reply = msgBox.exec()

		if reply != QMessageBox.AcceptRole:
			return
		recycle_action = RecycleAction(self._main_win._sess_wp)
		code = recycle_action.rec_restore(file_info)
		if code == RetCode.SUCCESS:
			self.getRecycleList()
		else:
			QMessageBox.information(self._main_win, "提示", "还原失败")

	def recycleDelete(self, file_info):
		msgBox = QMessageBox()
		msgBox.setWindowTitle('删除文件/文件夹')
		msgBox.setIcon(QMessageBox.Warning)
		icon = QIcon()
		icon.addPixmap(QPixmap(":/icon/icons/logo.png"), QIcon.Normal, QIcon.Off)
		msgBox.setWindowIcon(icon)
		file_type = '文件夹' if file_info.isFolder else '文件'
		msgBox.setText(f'确定要删除{file_type}[{file_info.name}]吗？')
		btnOK = msgBox.addButton('确定', QMessageBox.AcceptRole)
		btnCancel = msgBox.addButton('取消', QMessageBox.RejectRole)
		msgBox.setDefaultButton(btnOK)
		reply = msgBox.exec()

		if reply != QMessageBox.AcceptRole:
			return
		recycle_action = RecycleAction(self._main_win._sess_wp)
		code = recycle_action.rec_delete(file_info)
		if code == RetCode.SUCCESS:
			self.getRecycleList()
		else:
			QMessageBox.information(self._main_win, "提示", "删除失败")